package com.coder.algorithm.leetcode;

/**
 * [35. 搜索插入位置](https://leetcode-cn.com/problems/search-insert-position)
 *
 * @author yuhushuan
 * @date 2020/10/18 22:58
 */
class l_0035 {
    public static void main(String[] args) {
        l_0035 l = new l_0035();

        System.out.println(l.searchInsert(new int[]{1, 3, 5, 6}, 5));
        System.out.println(l.searchInsert(new int[]{1, 3, 5, 6}, 2));
        System.out.println(l.searchInsert(new int[]{1, 3, 5, 6}, 7));
        System.out.println(l.searchInsert(new int[]{1, 3, 5, 6}, 0));
    }

    public int searchInsert(int[] nums, int target) {
        if (nums == null) {
            return -1;
        }
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int mid = left + ((right - left + 1) >> 1);
            if (target < nums[mid]) {// left
                right = mid - 1;
            } else {// right
                left = mid;
            }
        }
        if (nums[right] < target)
            right = right + 1;
        return right;
    }


    public int searchInsert1(int[] nums, int target) {
        if (nums == null) {
            return -1;
        }
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] == target) {// 存在值
                return mid;
            } else if (target < nums[mid]) {// left
                right = mid - 1;
            } else {// right
                left = mid + 1;
            }
        }
        if (nums[left] < target)
            left = left + 1;
        return left;
    }
}
